<template>
  <div class="customer-form">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="breadcrumb-section">
        <el-breadcrumb separator="/">
          <el-breadcrumb-item>
            <el-button text @click="goBack" :icon="ArrowLeft">返回</el-button>
          </el-breadcrumb-item>
          <el-breadcrumb-item>CRM系统</el-breadcrumb-item>
          <el-breadcrumb-item>客户档案管理</el-breadcrumb-item>
          <el-breadcrumb-item>客户列表</el-breadcrumb-item>
          <el-breadcrumb-item>{{ isEditMode ? '编辑客户' : '新增客户' }}</el-breadcrumb-item>
        </el-breadcrumb>
      </div>

      <div class="form-title-section">
        <h1>{{ isEditMode ? '编辑客户信息' : '新增客户档案' }}</h1>
        <p>{{ isEditMode ? '修改现有客户的详细信息' : '录入新客户的完整档案信息' }}</p>
        
        <!-- 进度条 -->
        <div class="progress-section">
          <div class="progress-bar">
            <div class="progress-fill" :style="{ width: progressPercentage + '%' }"></div>
          </div>
          <span class="progress-text">{{ currentStep }}/{{ totalSteps }} - {{ progressPercentage }}%</span>
        </div>
      </div>
    </div>

    <!-- 分步导航 -->
    <div class="step-navigation">
      <div class="steps-container">
        <div 
          v-for="(step, index) in steps" 
          :key="step.id"
          class="step-item"
          :class="{ 
            active: currentStep === index + 1, 
            completed: currentStep > index + 1,
            disabled: currentStep < index + 1 
          }"
          @click="goToStep(index + 1)"
        >
          <div class="step-number">
            <el-icon v-if="currentStep > index + 1"><Check /></el-icon>
            <span v-else>{{ index + 1 }}</span>
          </div>
          <div class="step-content">
            <div class="step-title">{{ step.title }}</div>
            <div class="step-description">{{ step.description }}</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 加载状态 -->
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="8" animated />
        <div class="loading-text">正在加载客户数据...</div>
      </div>
      
      <!-- 左侧表单区域 -->
      <div v-else class="form-area">
        <el-form
          ref="formRef"
          :model="formData"
          :rules="formRules"
          label-position="top"
          class="customer-form-content"
        >
          <!-- 第一步：基础信息 -->
          <div v-show="currentStep === 1" class="step-content">
            <div class="section-header">
              <h3><el-icon><User /></el-icon>基础信息</h3>
              <p>填写客户的基本个人信息</p>
            </div>

            <div class="form-sections">
              <div class="form-section">
                <h4>个人基本信息</h4>
                <el-row :gutter="16">
                  <el-col :span="12">
                    <el-form-item label="客户姓名" prop="customerName" required>
                      <el-input v-model="formData.customerName" placeholder="请输入客户姓名" clearable />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="性别" prop="gender" required>
                      <el-radio-group v-model="formData.gender">
                        <el-radio value="男">男</el-radio>
                        <el-radio value="女">女</el-radio>
                      </el-radio-group>
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="16">
                  <el-col :span="12">
                    <el-form-item label="出生日期" prop="birthDate" required>
                      <el-date-picker
                        v-model="formData.birthDate"
                        type="date"
                        placeholder="请选择出生日期"
                        style="width: 100%"
                        value-format="YYYY-MM-DD"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="身份证号" prop="idCard" required>
                      <el-input v-model="formData.idCard" placeholder="请输入身份证号" clearable />
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="16">
                  <el-col :span="12">
                    <el-form-item label="工作状态" prop="workStatus" required>
                      <el-select v-model="formData.workStatus" placeholder="请选择工作状态" style="width: 100%">
                        <el-option label="在职" value="在职" />
                        <el-option label="退休" value="退休" />
                        <el-option label="待业" value="待业" />
                        <el-option label="其他" value="其他" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="职业" prop="occupation">
                      <el-input v-model="formData.occupation" placeholder="请输入职业" clearable />
                    </el-form-item>
                  </el-col>
                </el-row>
              </div>

              <div class="form-section">
                <h4>联系方式</h4>
                <el-row :gutter="16">
                  <el-col :span="12">
                    <el-form-item label="主要手机" prop="primaryPhone" required>
                      <el-input v-model="formData.primaryPhone" placeholder="请输入主要手机号" clearable />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="备用手机" prop="backupPhone">
                      <el-input v-model="formData.backupPhone" placeholder="请输入备用手机号" clearable />
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="16">
                  <el-col :span="12">
                    <el-form-item label="微信号" prop="wechat">
                      <el-input v-model="formData.wechat" placeholder="请输入微信号" clearable />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="电子邮箱" prop="email">
                      <el-input v-model="formData.email" placeholder="请输入电子邮箱" clearable />
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-form-item label="通讯地址" prop="address">
                  <el-input v-model="formData.address" placeholder="请输入详细地址" clearable />
                </el-form-item>
              </div>

              <div class="form-section">
                <h4>紧急联系人</h4>
                <el-row :gutter="16">
                  <el-col :span="8">
                    <el-form-item label="联系人姓名" prop="emergencyContactName" required>
                      <el-input v-model="formData.emergencyContactName" placeholder="请输入姓名" clearable />
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="关系" prop="emergencyContactRelation" required>
                      <el-select v-model="formData.emergencyContactRelation" placeholder="请选择关系" style="width: 100%">
                        <el-option label="配偶" value="配偶" />
                        <el-option label="子女" value="子女" />
                        <el-option label="亲属" value="亲属" />
                        <el-option label="朋友" value="朋友" />
                        <el-option label="其他" value="其他" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="联系电话" prop="emergencyContactPhone" required>
                      <el-input v-model="formData.emergencyContactPhone" placeholder="请输入联系电话" clearable />
                    </el-form-item>
                  </el-col>
                </el-row>
              </div>
              
              <!-- 客户标签 -->
              <div class="form-section">
                <h4>客户标签（可选）</h4>
                <p class="section-description">选择适合的标签，便于后续管理和分类</p>
                <div class="tag-selection-container">
                  <div class="tag-categories">
                    <div 
                      v-for="(tags, category) in availableTags" 
                      :key="category"
                      class="tag-category"
                    >
                      <h5>{{ category }}</h5>
                      <div class="tag-options">
                        <el-checkbox-group v-model="formData.selectedTags">
                          <el-checkbox
                            v-for="tag in tags"
                            :key="tag.name"
                            :value="tag.name"
                            :label="tag.name"
                            class="tag-checkbox"
                          >
                            {{ tag.name }}
                          </el-checkbox>
                        </el-checkbox-group>
                      </div>
                    </div>
                  </div>
                  <div class="selected-tags-preview" v-if="formData.selectedTags && formData.selectedTags.length > 0">
                    <h5>已选标签</h5>
                    <div class="selected-tags">
                      <el-tag
                        v-for="(tag, index) in formData.selectedTags"
                        :key="typeof tag === 'string' ? tag : tag.name || `tag-${index}`"
                        :type="getTagTypeByName(typeof tag === 'string' ? tag : tag.name)"
                        size="small"
                        closable
                        @close="removeSelectedTag(typeof tag === 'string' ? tag : tag.name)"
                      >
                        {{ typeof tag === 'string' ? tag : tag.name }}
                      </el-tag>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 第二步：旅游偏好 -->
          <div v-show="currentStep === 2" class="step-content">
            <div class="section-header">
              <h3><el-icon><MapLocation /></el-icon>旅游偏好</h3>
              <p>了解客户的出行习惯和偏好</p>
            </div>

            <div class="form-sections">
              <div class="form-section">
                <h4>预算信息</h4>
                <el-row :gutter="16">
                  <el-col :span="12">
                    <el-form-item label="预算类型" prop="budgetRange">
                      <el-select v-model="formData.budgetRange" placeholder="请选择预算类型" style="width: 100%">
                        <el-option label="经济型" value="经济型" />
                        <el-option label="舒适型" value="舒适型" />
                        <el-option label="品质型" value="品质型" />
                        <el-option label="豪华型" value="豪华型" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="支付偏好" prop="paymentPreference">
                      <el-select v-model="formData.paymentPreference" placeholder="请选择支付方式" style="width: 100%">
                        <el-option label="现金支付" value="现金支付" />
                        <el-option label="银行转账" value="银行转账" />
                        <el-option label="微信支付" value="微信支付" />
                        <el-option label="支付宝" value="支付宝" />
                        <el-option label="刷卡" value="刷卡" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>
              </div>

              <div class="form-section">
                <h4>目的地偏好</h4>
                <el-row :gutter="16">
                  <el-col :span="12">
                    <el-form-item label="国内地域" prop="domesticRegions">
                      <el-select v-model="formData.domesticRegions" multiple placeholder="请选择国内地域" style="width: 100%">
                        <el-option label="华北" value="华北" />
                        <el-option label="华东" value="华东" />
                        <el-option label="华南" value="华南" />
                        <el-option label="华中" value="华中" />
                        <el-option label="西南" value="西南" />
                        <el-option label="西北" value="西北" />
                        <el-option label="东北" value="东北" />
                        <el-option label="港澳台" value="港澳台" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="国际地域" prop="internationalRegions">
                      <el-select v-model="formData.internationalRegions" multiple placeholder="请选择国际地域" style="width: 100%">
                        <el-option label="东南亚" value="东南亚" />
                        <el-option label="日韩" value="日韩" />
                        <el-option label="欧洲" value="欧洲" />
                        <el-option label="澳新" value="澳新" />
                        <el-option label="美洲" value="美洲" />
                        <el-option label="其他" value="其他" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-form-item label="景观偏好" prop="landscapePreferences">
                  <el-checkbox-group v-model="formData.landscapePreferences">
                    <el-checkbox value="自然风光">自然风光</el-checkbox>
                    <el-checkbox value="历史古迹">历史古迹</el-checkbox>
                    <el-checkbox value="海滨度假">海滨度假</el-checkbox>
                    <el-checkbox value="温泉养生">温泉养生</el-checkbox>
                    <el-checkbox value="美食文化">美食文化</el-checkbox>
                    <el-checkbox value="民俗风情">民俗风情</el-checkbox>
                    <el-checkbox value="都市观光">都市观光</el-checkbox>
                    <el-checkbox value="摄影采风">摄影采风</el-checkbox>
                    <el-checkbox value="购物娱乐">购物娱乐</el-checkbox>
                  </el-checkbox-group>
                </el-form-item>
              </div>

              <div class="form-section">
                <h4>出行安排</h4>
                <el-row :gutter="16">
                  <el-col :span="12">
                    <el-form-item label="出行时长" prop="durationPreference">
                      <el-select v-model="formData.durationPreference" placeholder="请选择出行时长" style="width: 100%">
                        <el-option label="短途 (1-3天)" value="短途" />
                        <el-option label="中途 (4-7天)" value="中途" />
                        <el-option label="长途 (8-15天)" value="长途" />
                        <el-option label="超长 (16天以上)" value="超长" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="住宿标准" prop="accommodationStandard">
                      <el-select v-model="formData.accommodationStandard" placeholder="请选择住宿标准" style="width: 100%">
                        <el-option label="经济型酒店" value="经济型酒店" />
                        <el-option label="舒适型酒店" value="舒适型酒店" />
                        <el-option label="高档酒店" value="高档酒店" />
                        <el-option label="度假村" value="度假村" />
                        <el-option label="民宿客栈" value="民宿客栈" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-form-item label="交通偏好" prop="transportPreferences">
                  <el-checkbox-group v-model="formData.transportPreferences">
                    <el-checkbox value="飞机">飞机</el-checkbox>
                    <el-checkbox value="高铁">高铁</el-checkbox>
                    <el-checkbox value="普通火车">普通火车</el-checkbox>
                    <el-checkbox value="大巴车">大巴车</el-checkbox>
                    <el-checkbox value="自驾车">自驾车</el-checkbox>
                  </el-checkbox-group>
                </el-form-item>
              </div>
            </div>
          </div>

          <!-- 第三步：健康状况 -->
          <div v-show="currentStep === 3" class="step-content">
            <div class="section-header">
              <h3><el-icon><User /></el-icon>健康状况</h3>
              <p>了解客户的健康状态，确保出行安全</p>
            </div>

            <div class="form-sections">
              <div class="form-section">
                <h4>基本健康状况</h4>
                <el-row :gutter="16">
                  <el-col :span="12">
                    <el-form-item label="整体健康状况" prop="healthStatus" required>
                      <el-select v-model="formData.healthStatus" placeholder="请选择健康状况" style="width: 100%">
                        <el-option label="健康良好" value="健康良好" />
                        <el-option label="健康一般" value="健康一般" />
                        <el-option label="健康较差" value="健康较差" />
                        <el-option label="健康很差" value="健康很差" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="行动能力" prop="mobilityAbility">
                      <el-select v-model="formData.mobilityAbility" placeholder="请选择行动能力" style="width: 100%">
                        <el-option label="行动自如" value="行动自如" />
                        <el-option label="轻微受限" value="轻微受限" />
                        <el-option label="需要辅助" value="需要辅助" />
                        <el-option label="轮椅出行" value="轮椅出行" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>
              </div>

              <div class="form-section">
                <h4>疾病信息</h4>
                <el-form-item label="慢性疾病" prop="chronicDiseases">
                  <el-checkbox-group v-model="formData.chronicDiseases">
                    <el-checkbox value="高血压">高血压</el-checkbox>
                    <el-checkbox value="糖尿病">糖尿病</el-checkbox>
                    <el-checkbox value="心脏病">心脏病</el-checkbox>
                    <el-checkbox value="关节炎">关节炎</el-checkbox>
                    <el-checkbox value="骨质疏松">骨质疏松</el-checkbox>
                    <el-checkbox value="其他">其他</el-checkbox>
                  </el-checkbox-group>
                </el-form-item>

                <el-form-item label="用药情况" prop="medicationInfo">
                  <el-input
                    v-model="formData.medicationInfo"
                    type="textarea"
                    :rows="3"
                    placeholder="请详细描述日常用药情况，包括药品名称、剂量、服用时间等"
                  />
                </el-form-item>

                <el-form-item label="饮食限制" prop="dietaryRestrictions">
                  <el-checkbox-group v-model="formData.dietaryRestrictions">
                    <el-checkbox value="无特殊要求">无特殊要求</el-checkbox>
                    <el-checkbox value="低盐低脂">低盐低脂</el-checkbox>
                    <el-checkbox value="糖尿病餐">糖尿病餐</el-checkbox>
                    <el-checkbox value="清淡饮食">清淡饮食</el-checkbox>
                    <el-checkbox value="素食">素食</el-checkbox>
                  </el-checkbox-group>
                </el-form-item>

                <el-form-item label="保险情况" prop="insuranceInfo">
                  <el-input
                    v-model="formData.insuranceInfo"
                    type="textarea"
                    :rows="2"
                    placeholder="请描述医疗保险和旅游保险情况"
                  />
                </el-form-item>
              </div>
            </div>
          </div>

          <!-- 第四步：家庭信息 -->
          <div v-show="currentStep === 4" class="step-content">
            <div class="section-header">
              <h3><el-icon><UserFilled /></el-icon>家庭信息</h3>
              <p>了解客户的家庭情况和决策模式</p>
            </div>

            <div class="form-sections">
              <div class="form-section">
                <h4>家庭基本信息</h4>
                <el-row :gutter="16">
                  <el-col :span="12">
                    <el-form-item label="婚姻状况" prop="maritalStatus">
                      <el-select v-model="formData.maritalStatus" placeholder="请选择婚姻状况" style="width: 100%">
                        <el-option label="已婚" value="已婚" />
                        <el-option label="丧偶" value="丧偶" />
                        <el-option label="离异" value="离异" />
                        <el-option label="未婚" value="未婚" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="决策模式" prop="decisionPattern">
                      <el-select v-model="formData.decisionPattern" placeholder="请选择决策模式" style="width: 100%">
                        <el-option label="自主决策" value="自主决策" />
                        <el-option label="咨询决策" value="咨询决策" />
                        <el-option label="共同决策" value="共同决策" />
                        <el-option label="代为决策" value="代为决策" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>
              </div>

              <div v-if="formData.maritalStatus === '已婚'" class="form-section">
                <h4>配偶信息</h4>
                <el-row :gutter="16">
                  <el-col :span="8">
                    <el-form-item label="配偶姓名" prop="spouseName">
                      <el-input v-model="formData.spouseName" placeholder="请输入配偶姓名" clearable />
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="配偶年龄" prop="spouseAge">
                      <el-input-number v-model="formData.spouseAge" :min="18" :max="120" style="width: 100%" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="配偶联系方式" prop="spousePhone">
                      <el-input v-model="formData.spousePhone" placeholder="请输入联系方式" clearable />
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-form-item label="同行情况" prop="spouseTravelTogether">
                  <el-radio-group v-model="formData.spouseTravelTogether">
                    <el-radio value="经常同行">经常同行</el-radio>
                    <el-radio value="偶尔同行">偶尔同行</el-radio>
                    <el-radio value="从不同行">从不同行</el-radio>
                  </el-radio-group>
                </el-form-item>
              </div>

              <div class="form-section">
                <h4>决策影响因素</h4>
                <el-form-item label="主要考虑因素" prop="influenceFactors">
                  <el-checkbox-group v-model="formData.influenceFactors">
                    <el-checkbox value="价格因素">价格因素</el-checkbox>
                    <el-checkbox value="安全因素">安全因素</el-checkbox>
                    <el-checkbox value="健康因素">健康因素</el-checkbox>
                    <el-checkbox value="家人意见">家人意见</el-checkbox>
                    <el-checkbox value="朋友推荐">朋友推荐</el-checkbox>
                  </el-checkbox-group>
                </el-form-item>
              </div>
            </div>
          </div>
        </el-form>
      </div>

      <!-- 右侧预览区域 -->
      <div class="preview-area">
        <div class="preview-card">
          <div class="preview-header">
            <h3><el-icon><View /></el-icon>信息预览</h3>
            <div class="completeness-indicator">
              <span>完整度：{{ completenessPercentage }}%</span>
              <div class="completeness-bar">
                <div class="completeness-fill" :style="{ width: completenessPercentage + '%' }"></div>
              </div>
            </div>
          </div>

          <div class="preview-content">
            <div class="preview-section" v-if="formData.customerName">
              <h4>基础信息</h4>
              <div class="preview-item">
                <span class="label">姓名：</span>
                <span class="value">{{ formData.customerName }}</span>
              </div>
              <div class="preview-item" v-if="formData.gender">
                <span class="label">性别：</span>
                <span class="value">{{ formData.gender }}</span>
              </div>
              <div class="preview-item" v-if="formData.primaryPhone">
                <span class="label">电话：</span>
                <span class="value">{{ formData.primaryPhone }}</span>
              </div>
            </div>

            <div class="preview-section" v-if="formData.budgetRange || formData.domesticRegions?.length">
              <h4>旅游偏好</h4>
              <div class="preview-item" v-if="formData.budgetRange">
                <span class="label">预算：</span>
                <span class="value">{{ formData.budgetRange }}</span>
              </div>
              <div class="preview-item" v-if="formData.domesticRegions?.length">
                <span class="label">目的地：</span>
                <span class="value">{{ formData.domesticRegions.join('、') }}</span>
              </div>
            </div>

            <div class="preview-section" v-if="formData.healthStatus">
              <h4>健康状况</h4>
              <div class="preview-item">
                <span class="label">整体状况：</span>
                <span class="value">{{ formData.healthStatus }}</span>
              </div>
              <div class="preview-item" v-if="formData.chronicDiseases?.length">
                <span class="label">慢性疾病：</span>
                <span class="value">{{ formData.chronicDiseases.join('、') }}</span>
              </div>
            </div>

            <div class="preview-section" v-if="formData.maritalStatus">
              <h4>家庭信息</h4>
              <div class="preview-item">
                <span class="label">婚姻状况：</span>
                <span class="value">{{ formData.maritalStatus }}</span>
              </div>
              <div class="preview-item" v-if="formData.spouseName">
                <span class="label">配偶：</span>
                <span class="value">{{ formData.spouseName }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 操作按钮区域 -->
    <div class="action-buttons">
      <div class="left-actions">
        <el-button @click="saveDraft" :icon="Document">保存草稿</el-button>
        <el-button @click="goBack" :icon="ArrowLeft">取消</el-button>
      </div>

      <div class="right-actions">
        <el-button v-if="currentStep > 1" @click="previousStep" :icon="ArrowLeft">
          上一步
        </el-button>
        <el-button v-if="currentStep < totalSteps" type="primary" @click="nextStep" :icon="ArrowRight">
          下一步
        </el-button>
        <el-button v-else type="success" @click="submitForm" :icon="Check" :loading="submitting">
          完成提交
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  ArrowLeft, ArrowRight, User, MapLocation, UserFilled, Check, Document, View
} from '@element-plus/icons-vue'
import { customerAPI } from '@/api/customer'
import type { CreateCustomerRequest, CustomerBasicInfo } from '@/api/customer'

// 路由相关
const route = useRoute()
const router = useRouter()
const isEditMode = computed(() => !!route.params.id)
const customerId = computed(() => route.params.id as string)

// 响应式数据
const currentStep = ref(1)
const totalSteps = 4
const submitting = ref(false)
const loading = ref(false)
const formRef = ref()

// 步骤配置
const steps = [
  {
    id: 1,
    title: '基础信息',
    description: '个人基本信息'
  },
  {
    id: 2,
    title: '旅游偏好',
    description: '出行习惯偏好'
  },
  {
    id: 3,
    title: '健康状况',
    description: '健康档案信息'
  },
  {
    id: 4,
    title: '家庭信息',
    description: '家庭社交信息'
  }
]

// 表单数据
const formData = ref({
  // 基础信息
  customerName: '',
  gender: '',
  birthDate: '',
  idCard: '',
  workStatus: '',
  occupation: '',
  primaryPhone: '',
  backupPhone: '',
  wechat: '',
  email: '',
  address: '',
  emergencyContactName: '',
  emergencyContactRelation: '',
  emergencyContactPhone: '',
  
  // 客户标签
  selectedTags: [] as string[],
  
  // 旅游偏好
  budgetRange: '',
  paymentPreference: '',
  domesticRegions: [],
  internationalRegions: [],
  landscapePreferences: [],
  durationPreference: '',
  accommodationStandard: '',
  transportPreferences: [],
  
  // 健康状况
  healthStatus: '',
  mobilityAbility: '',
  chronicDiseases: [],
  medicationInfo: '',
  dietaryRestrictions: [],
  insuranceInfo: '',
  
  // 家庭信息
  maritalStatus: '',
  decisionPattern: '',
  spouseName: '',
  spouseAge: null,
  spousePhone: '',
  spouseTravelTogether: '',
  influenceFactors: []
})

// 表单验证规则
const formRules = {
  customerName: [
    { required: true, message: '请输入客户姓名', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  birthDate: [
    { required: true, message: '请选择出生日期', trigger: 'change' }
  ],
  idCard: [
    { required: true, message: '请输入身份证号', trigger: 'blur' },
    { pattern: /^\d{17}[\dXx]$/, message: '身份证号格式不正确', trigger: 'blur' }
  ],
  workStatus: [
    { required: true, message: '请选择工作状态', trigger: 'change' }
  ],
  primaryPhone: [
    { required: true, message: '请输入主要手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
  ],
  emergencyContactName: [
    { required: true, message: '请输入紧急联系人姓名', trigger: 'blur' }
  ],
  emergencyContactRelation: [
    { required: true, message: '请选择紧急联系人关系', trigger: 'change' }
  ],
  emergencyContactPhone: [
    { required: true, message: '请输入紧急联系人电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
  ],
  healthStatus: [
    { required: true, message: '请选择健康状况', trigger: 'change' }
  ]
}

// 可选标签数据
const availableTags = {
  '价值分类': [
    { name: 'VIP客户', description: '高价值客户，优先服务' },
    { name: '优质客户', description: '消费能力强，忠诚度高' },
    { name: '普通客户', description: '一般消费客户' },
    { name: '价格敏感客户', description: '对价格比较敏感' }
  ],
  '服务特点': [
    { name: '易沟通', description: '沟通顺畅，配合度高' },
    { name: '需要关怀', description: '需要更多关注和照顾' },
    { name: '决策慢', description: '决策周期较长' },
    { name: '冲动消费', description: '容易冲动下单' }
  ],
  '出行特点': [
    { name: '喜欢跟团', description: '偏好跟团旅游' },
    { name: '偏爱自由行', description: '喜欢自由行方式' },
    { name: '只走精品线', description: '只选择精品旅游线路' },
    { name: '价格敏感', description: '对价格比较敏感' }
  ],
  '健康状态': [
    { name: '身体健康', description: '身体状况良好' },
    { name: '需要照顾', description: '需要特殊照顾' },
    { name: '行动不便', description: '行动存在一定困难' }
  ],
  '消费习惯': [
    { name: '多次消费', description: '有过多次消费记录' },
    { name: '首次消费', description: '首次消费客户' },
    { name: '犹豫不决', description: '决策时间较长' },
    { name: '果断下单', description: '决策速度快' }
  ]
}

// 标签相关方法
const getTagTypeByName = (tagName: string | undefined) => {
  if (!tagName) return 'default'
  
  for (const [category, tags] of Object.entries(availableTags)) {
    if (tags.some(tag => tag.name === tagName)) {
      const typeMap: Record<string, string> = {
        '价值分类': 'success',
        '服务特点': 'primary',
        '出行特点': 'warning',
        '健康状态': 'danger',
        '消费习惯': 'info'
      }
      return typeMap[category] || 'default'
    }
  }
  return 'default'
}

const removeSelectedTag = (tagName: string) => {
  const index = formData.value.selectedTags.findIndex(tag => {
    if (typeof tag === 'string') {
      return tag === tagName
    } else if (tag && typeof tag === 'object' && tag.name) {
      return tag.name === tagName
    }
    return false
  })
  if (index > -1) {
    formData.value.selectedTags.splice(index, 1)
  }
}

// 计算属性
const progressPercentage = computed(() => {
  return Math.round((currentStep.value / totalSteps) * 100)
})

const completenessPercentage = computed(() => {
  const requiredFields = [
    'customerName', 'gender', 'birthDate', 'idCard', 'workStatus', 
    'primaryPhone', 'emergencyContactName', 'emergencyContactRelation', 
    'emergencyContactPhone', 'healthStatus'
  ]
  
  const filledFields = requiredFields.filter(field => {
    const value = formData.value[field as keyof typeof formData.value]
    return value && value !== ''
  })
  
  return Math.round((filledFields.length / requiredFields.length) * 100)
})

// 方法
const goBack = () => {
  router.back()
}

const goToStep = (step: number) => {
  if (step <= currentStep.value || step === currentStep.value + 1) {
    currentStep.value = step
  }
}

const validateCurrentStep = async () => {
  if (!formRef.value) return true
  
  let fieldsToValidate: string[] = []
  
  switch (currentStep.value) {
    case 1:
      fieldsToValidate = [
        'customerName', 'gender', 'birthDate', 'idCard', 'workStatus',
        'primaryPhone', 'emergencyContactName', 'emergencyContactRelation', 
        'emergencyContactPhone'
      ]
      break
    case 2:
      // 旅游偏好为可选项
      break
    case 3:
      fieldsToValidate = ['healthStatus']
      break
    case 4:
      // 家庭信息为可选项
      break
  }
  
  if (fieldsToValidate.length === 0) return true
  
  try {
    await formRef.value.validateField(fieldsToValidate)
    return true
  } catch (error) {
    ElMessage.error('请完善当前步骤的必填信息')
    return false
  }
}

const nextStep = async () => {
  const isValid = await validateCurrentStep()
  if (isValid && currentStep.value < totalSteps) {
    currentStep.value++
  }
}

const previousStep = () => {
  if (currentStep.value > 1) {
    currentStep.value--
  }
}

const saveDraft = async () => {
  try {
    // 这里可以实现保存草稿的逻辑
    ElMessage.success('草稿保存成功')
  } catch (error) {
    ElMessage.error('保存草稿失败')
  }
}

const submitForm = async () => {
  try {
    submitting.value = true
    
    // 验证整个表单
    await formRef.value.validate()
    
    // 构建提交数据
    const submitData: CreateCustomerRequest = {
      basicInfo: {
        customerName: formData.value.customerName,
        gender: formData.value.gender as '男' | '女',
        birthDate: formData.value.birthDate,
        idCard: formData.value.idCard,
        primaryPhone: formData.value.primaryPhone,
        backupPhone: formData.value.backupPhone || undefined,
        wechat: formData.value.wechat || undefined,
        email: formData.value.email || undefined,
        address: formData.value.address || undefined,
        emergencyContactName: formData.value.emergencyContactName,
        emergencyContactRelation: formData.value.emergencyContactRelation as any,
        emergencyContactPhone: formData.value.emergencyContactPhone,
        workStatus: formData.value.workStatus as any,
        occupation: formData.value.occupation || undefined,
        customerStatus: '潜在客户'
      }
    }
    
    if (isEditMode.value) {
      // 编辑模式
      await customerAPI.updateCustomer(parseInt(customerId.value), submitData.basicInfo)
      ElMessage.success('客户信息更新成功')
    } else {
      // 新增模式
      await customerAPI.createCustomer(submitData)
      ElMessage.success('客户创建成功')
    }
    
    // 返回客户列表页
    router.push('/customers')
    
  } catch (error) {
    console.error('Submit error:', error)
    ElMessage.error(isEditMode.value ? '更新客户失败' : '创建客户失败')
  } finally {
    submitting.value = false
  }
}

const loadCustomerData = async () => {
  if (!isEditMode.value) return
  
  loading.value = true
  try {
    const response = await customerAPI.getCustomerDetail(parseInt(customerId.value))
    
    if (!response || response.code !== 200 || !response.data) {
      throw new Error(response?.message || '获取客户数据失败')
    }
    
    const customer = response.data.basicInfo
    if (!customer) {
      throw new Error('客户基础信息不存在')
    }
    
    // 填充表单数据 - 使用安全的字段映射
    Object.assign(formData.value, {
      customerName: customer.customerName || '',
      gender: customer.gender || '',
      birthDate: customer.birthDate ? new Date(customer.birthDate) : '',
      idCard: customer.idCard || '',
      workStatus: customer.workStatus || '',
      occupation: customer.occupation || '',
      primaryPhone: customer.primaryPhone || '',
      backupPhone: customer.backupPhone || '',
      wechat: customer.wechat || '',
      email: customer.email || '',
      address: customer.address || '',
      emergencyContactName: customer.emergencyContactName || '',
      emergencyContactRelation: customer.emergencyContactRelation || '',
      emergencyContactPhone: customer.emergencyContactPhone || ''
    })
    
    // 获取完整的响应数据对象
    const responseData = response.data
    
    // 填充旅游偏好数据
    if (responseData.travelPreferences) {
      const preferences = responseData.travelPreferences
      Object.assign(formData.value, {
        budgetRange: preferences.budgetRange || '',
        paymentPreference: preferences.paymentPreference || '',
        domesticRegions: preferences.domesticRegions || [],
        internationalRegions: preferences.internationalRegions || [],
        landscapePreferences: preferences.landscapePreferences || [],
        durationPreference: preferences.durationPreference || '',
        accommodationStandard: preferences.accommodationStandard || '',
        transportPreferences: preferences.transportPreferences || []
      })
    }
    
    // 填充健康信息
    if (responseData.healthInfo) {
      const healthInfo = responseData.healthInfo
      Object.assign(formData.value, {
        healthStatus: healthInfo.healthStatus || '',
        mobilityAbility: healthInfo.mobilityAbility || '',
        chronicDiseases: healthInfo.chronicDiseases || [],
        medicationInfo: healthInfo.medicationInfo || ''
      })
    }
    
    // 填充家庭信息
    if (responseData.familyInfo) {
      const familyInfo = responseData.familyInfo
      Object.assign(formData.value, {
        maritalStatus: familyInfo.maritalStatus || '',
        spouseName: familyInfo.spouseInfo?.spouseName || '',
        spousePhone: familyInfo.spouseInfo?.spousePhone || '',
        spouseTravelTogether: familyInfo.spouseInfo?.spouseTravelTogether || '',
        influenceFactors: familyInfo.influenceFactors || []
      })
    }
    console.log(responseData)
    // 填充标签信息
    if (responseData.tags && Array.isArray(responseData.tags)) {
      const tagNames = responseData.tags
        .map(tag => {
          if (typeof tag === 'string') {
            return tag
          } else if (tag && typeof tag === 'object' && tag.name) {
            return String(tag.name) // 强制转换为字符串
          }
          return null
        })
        .filter(Boolean) // 过滤掉无效值
        .filter(name => typeof name === 'string') // 确保都是字符串
      
      // 设置标签名称数组
      formData.value.selectedTags = tagNames as string[]
    }
    
    ElMessage.success('客户数据加载成功')
    
  } catch (error) {
    ElMessage.error(`加载客户数据失败: ${error.message || '未知错误'}`)
  } finally {
    loading.value = false
  }
}

// 生命周期
onMounted(() => {
  if (isEditMode.value) {
    loadCustomerData()
  }
})
</script>

<style lang="scss" scoped>
.customer-form {
  padding: var(--apple-spacing-lg);
  background: var(--apple-background-primary);
  min-height: 100vh;

  // 页面头部
  .page-header {
    margin-bottom: var(--apple-spacing-lg);

    .breadcrumb-section {
      margin-bottom: var(--apple-spacing-md);

      .el-breadcrumb {
        :deep(.el-breadcrumb__item) {
          .el-breadcrumb__inner {
            color: var(--apple-text-secondary);
            
            &:hover {
              color: var(--apple-link-color);
            }
          }
        }
      }
    }

    .form-title-section {
      background: linear-gradient(135deg, #007AFF 0%, #5AC8FA 100%);
      padding: var(--apple-spacing-xl);
      border-radius: var(--apple-radius-lg);
      color: white;
      text-align: center;

      h1 {
        margin: 0 0 var(--apple-spacing-sm) 0;
        font-size: 2rem;
        font-weight: 700;
      }

      p {
        margin: 0 0 var(--apple-spacing-lg) 0;
        opacity: 0.9;
      }

      .progress-section {
        display: flex;
        align-items: center;
        justify-content: center;
        gap: var(--apple-spacing-md);

        .progress-bar {
          width: 200px;
          height: 8px;
          background: rgba(255, 255, 255, 0.3);
          border-radius: 4px;
          overflow: hidden;

          .progress-fill {
            height: 100%;
            background: white;
            transition: width 0.3s ease;
          }
        }

        .progress-text {
          font-size: 0.9rem;
          opacity: 0.9;
        }
      }
    }
  }

  // 分步导航
  .step-navigation {
    background: white;
    border-radius: var(--apple-radius-lg);
    box-shadow: var(--apple-shadow-light);
    margin-bottom: var(--apple-spacing-lg);
    overflow: hidden;

    .steps-container {
      display: flex;
      
      .step-item {
        flex: 1;
        padding: var(--apple-spacing-lg);
        display: flex;
        align-items: center;
        gap: var(--apple-spacing-md);
        cursor: pointer;
        transition: all 0.3s ease;
        border-right: 1px solid var(--apple-separator-primary);

        &:last-child {
          border-right: none;
        }

        &.active {
          background: rgba(0, 122, 255, 0.1);
          
          .step-number {
            background: #007AFF;
            color: white;
          }
          
          .step-title {
            color: #007AFF;
            font-weight: 600;
          }
        }

        &.completed {
          .step-number {
            background: #34C759;
            color: white;
          }
          
          .step-title {
            color: #34C759;
          }
        }

        &.disabled {
          opacity: 0.5;
          cursor: not-allowed;
        }

        &:hover:not(.disabled) {
          background: var(--apple-background-secondary);
        }

        .step-number {
          width: 40px;
          height: 40px;
          border-radius: 50%;
          background: var(--apple-background-secondary);
          display: flex;
          align-items: center;
          justify-content: center;
          font-weight: 600;
          color: var(--apple-text-secondary);
          transition: all 0.3s ease;
        }

        .step-content {
          .step-title {
            font-size: 1rem;
            font-weight: 600;
            color: var(--apple-text-primary);
            margin-bottom: 4px;
          }

          .step-description {
            font-size: 0.8rem;
            color: var(--apple-text-secondary);
          }
        }
      }
    }
  }

  // 主要内容区域
  .main-content {
    display: grid;
    grid-template-columns: 1fr 300px;
    gap: var(--apple-spacing-lg);
    margin-bottom: var(--apple-spacing-lg);

    // 左侧表单区域
    .form-area {
      background: white;
      border-radius: var(--apple-radius-lg);
      box-shadow: var(--apple-shadow-light);
      overflow: hidden;

      .customer-form-content {
        padding: var(--apple-spacing-xl);

        .step-content {
          .section-header {
            text-align: center;
            margin-bottom: var(--apple-spacing-xl);
            padding-bottom: var(--apple-spacing-lg);
            border-bottom: 1px solid var(--apple-separator-secondary);

            h3 {
              margin: 0 0 var(--apple-spacing-sm) 0;
              display: flex;
              align-items: center;
              justify-content: center;
              gap: var(--apple-spacing-sm);
              font-size: 1.5rem;
              font-weight: 600;
              color: var(--apple-text-primary);
            }

            p {
              margin: 0;
              color: var(--apple-text-secondary);
            }
          }

          .form-sections {
            .form-section {
              margin-bottom: var(--apple-spacing-xl);
              padding-bottom: var(--apple-spacing-lg);
              border-bottom: 1px solid var(--apple-separator-tertiary);

              &:last-child {
                border-bottom: none;
                margin-bottom: 0;
              }

              h4 {
                margin: 0 0 var(--apple-spacing-lg) 0;
                font-size: 1.1rem;
                font-weight: 600;
                color: var(--apple-text-primary);
              }
            }
          }
        }
      }
    }

    // 右侧预览区域
    .preview-area {
      .preview-card {
        background: white;
        border-radius: var(--apple-radius-lg);
        box-shadow: var(--apple-shadow-light);
        overflow: hidden;
        position: sticky;
        top: var(--apple-spacing-lg);

        .preview-header {
          background: var(--apple-background-secondary);
          padding: var(--apple-spacing-lg);
          border-bottom: 1px solid var(--apple-separator-primary);

          h3 {
            margin: 0 0 var(--apple-spacing-md) 0;
            display: flex;
            align-items: center;
            gap: var(--apple-spacing-sm);
            font-size: 1rem;
            font-weight: 600;
            color: var(--apple-text-primary);
          }

          .completeness-indicator {
            display: flex;
            align-items: center;
            gap: var(--apple-spacing-sm);
            font-size: 0.9rem;
            color: var(--apple-text-secondary);

            .completeness-bar {
              flex: 1;
              height: 6px;
              background: var(--apple-background-tertiary);
              border-radius: 3px;
              overflow: hidden;

              .completeness-fill {
                height: 100%;
                background: var(--apple-success-color);
                transition: width 0.3s ease;
              }
            }
          }
        }

        .preview-content {
          padding: var(--apple-spacing-lg);

          .preview-section {
            margin-bottom: var(--apple-spacing-lg);

            &:last-child {
              margin-bottom: 0;
            }

            h4 {
              margin: 0 0 var(--apple-spacing-sm) 0;
              font-size: 0.9rem;
              font-weight: 600;
              color: var(--apple-text-primary);
              border-bottom: 1px solid var(--apple-separator-tertiary);
              padding-bottom: 4px;
            }

            .preview-item {
              display: flex;
              margin-bottom: 4px;
              font-size: 0.8rem;

              .label {
                color: var(--apple-text-secondary);
                width: 60px;
                flex-shrink: 0;
              }

              .value {
                color: var(--apple-text-primary);
                word-break: break-all;
              }
            }
          }
        }
      }
    }
  }

  // 操作按钮区域
  .action-buttons {
    background: white;
    padding: var(--apple-spacing-lg);
    border-radius: var(--apple-radius-lg);
    box-shadow: var(--apple-shadow-light);
    display: flex;
    justify-content: space-between;
    align-items: center;

    .left-actions, .right-actions {
      display: flex;
      gap: var(--apple-spacing-sm);
    }
  }

  // 响应式设计
  @media (max-width: 1200px) {
    .main-content {
      grid-template-columns: 1fr 250px;
    }
  }

  @media (max-width: 768px) {
    padding: var(--apple-spacing-md);

    .main-content {
      grid-template-columns: 1fr;
      
      .preview-area {
        order: -1;
        
        .preview-card {
          position: static;
        }
      }
    }

    .step-navigation .steps-container {
      flex-direction: column;
      
      .step-item {
        border-right: none;
        border-bottom: 1px solid var(--apple-separator-primary);
        
        &:last-child {
          border-bottom: none;
        }
      }
    }

    .action-buttons {
      flex-direction: column;
      gap: var(--apple-spacing-md);
      
      .left-actions, .right-actions {
        width: 100%;
        justify-content: center;
      }
    }
  }

  // 标签选择相关样式
  .tag-selection-container {
    border: 1px solid #e1e5e9;
    border-radius: var(--apple-radius-md);
    padding: var(--apple-spacing-lg);
    background: #fafbfc;

    .tag-categories {
      margin-bottom: var(--apple-spacing-lg);

      .tag-category {
        margin-bottom: var(--apple-spacing-md);

        h5 {
          margin: 0 0 var(--apple-spacing-sm) 0;
          color: #1d1d1f;
          font-size: 0.9rem;
          font-weight: 600;
        }

      }
    }

    .selected-tags-preview {
      border-top: 1px solid #d2d2d7;
      padding-top: var(--apple-spacing-md);

      h5 {
        margin: 0 0 var(--apple-spacing-sm) 0;
        color: #1d1d1f;
        font-size: 0.9rem;
        font-weight: 600;
      }

      .selected-tags {
        display: flex;
        flex-wrap: wrap;
        gap: var(--apple-spacing-sm);
      }
    }
  }

  .section-description {
    font-size: 0.85rem;
    color: #86868b;
    margin: 0 0 var(--apple-spacing-md) 0;
    line-height: 1.4;
  }

  // 加载状态样式
  .loading-container {
    background: white;
    border-radius: var(--apple-radius-lg);
    padding: var(--apple-spacing-xl);
    box-shadow: var(--apple-shadow-light);

    .loading-text {
      text-align: center;
      margin-top: var(--apple-spacing-lg);
      color: #86868b;
      font-size: 0.9rem;
    }
  }
}
</style>